package com.beidouapp.mvc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.beidouapp.cache.impl.RedisDefaultAppCacheHelper;
import com.beidouapp.common.contant.SecurityContant;
import com.beidouapp.common.util.JSONUtils;
import com.beidouapp.common.util.SystemConfig;
import com.beidouapp.domain.pojo.ChinaData;
import com.beidouapp.domain.pojo.Engineer;
import com.beidouapp.domain.pojo.EngineerPos;
import com.beidouapp.domain.pojo.StatisData;
import com.beidouapp.domain.vo.ProjectVo;
import com.beidouapp.exception.BusinessException;
import com.beidouapp.security.model.ReturnDataInfo;
import com.beidouapp.service.EmployeeService;
import com.beidouapp.service.EngineerService;
import com.beidouapp.service.OrganizationService;
import com.beidouapp.service.UserService;

/**
 *  用户管理{论坛同步用户/咨询客户}
 */
@Controller
@RequestMapping(value = "/member")
public class MemberController {

    private static Logger logger = LoggerFactory.getLogger(MemberController.class);

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrganizationService organizationService;
    
    @Autowired
    private EngineerService engineerService;
    @Autowired
    private RedisDefaultAppCacheHelper redisCache;
    static String CHINA_STATIS_KEY="_CHINA_STATIS_KEY";
    static  long  EXPIRE_TIME=15;
    /**
     *  
     *  工程师位置分布图
     *  
     */
    @RequestMapping(value = "/showEngineerPos", method = RequestMethod.GET)
    public ModelAndView showEngineerPosition(HttpSession session) {
        ModelAndView view = new ModelAndView();
        Map<String, Object>  totalMap=  engineerService.getDistributeTotal();
        view.addObject("engineerTotal", totalMap.get("ENGINEER_TOTAL"));
        view.addObject("projectTotal", totalMap.get("PROJECT_TOTAL"));
        view.setViewName("engineer/engineer_position");
        return view;
    }
    @RequestMapping(value = "/showMonthlyDatasChart", method = RequestMethod.GET)
    public ModelAndView showMonthlyDatasChart(HttpSession session) {
        ModelAndView view = new ModelAndView();
        Map<String, Object>  totalMap=  engineerService.getDistributeTotal();
        view.addObject("engineerTotal", totalMap.get("ENGINEER_TOTAL"));
        view.addObject("projectTotal", totalMap.get("PROJECT_TOTAL"));
        view.setViewName("engineer/monthly_chart");
        return view;
    }
    
    
    /**
     *  跳转到用户列表页面
     *  
     */
    @RequestMapping(value = "/page/list", method = RequestMethod.GET)
    public ModelAndView forward2EmpPage(HttpSession session) {
        ModelAndView view = new ModelAndView();
        view.setViewName("member/member_list");
        return view;
    }
    
    /**
     * 
     *  获取列表
     *  
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/list", method = RequestMethod.GET)
    public
    @ResponseBody
    ReturnDataInfo<Engineer> listMember(HttpSession session, HttpServletRequest request, @RequestParam(value = "iDisplayStart", required = false, defaultValue = "0") Integer offset, @RequestParam(value = "iDisplayLength", required = false, defaultValue = "10") Integer limit, @RequestParam(value = "globalSearch", required = false, defaultValue = "{}") String globalSearch) {
        try {
            Map paramters = new HashMap();
            if (globalSearch != null) {
                JSONObject jsonObject = JSONObject.fromObject(globalSearch);
                paramters.putAll(jsonObject);
            }
            if(!paramters.containsKey("queryValue")){
            	paramters.put("queryValue", "");
            }
            paramters.putAll(request.getParameterMap());
          /* List<Engineer> engineers = engineerService.findEngineersByMap(paramters, offset, limit);*/
            /*Integer totalCount =  engineerService.findEngineersCountByMap(paramters);*/
            List<Engineer> engineers=new ArrayList<>();
            Integer totalCount=0;
             return ReturnDataInfo.createSuccessfulExecuteResults(engineers, offset, limit, totalCount.longValue());
        } catch (Exception ex) {
            logger.error("获取工程师用户列表失败", ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }


    /**
     *  
     *  //跳转到新增咨询客户页面
     *  
     */
    @RequestMapping(value = "/page/add", method = RequestMethod.GET)
    public ModelAndView addEmpPage(HttpSession session) {
        ModelAndView view = new ModelAndView();
        

        view.setViewName("member/member_add");
        return view;
    }




    /**
     * 
     * 工程师修改页面
     * 
     */
    @RequestMapping(value = "/page/edit/{id}", method = RequestMethod.GET)
    public ModelAndView modifyMemberPage(HttpSession session, @PathVariable Integer id) {
        ModelAndView view = new ModelAndView();
        Engineer engineer= engineerService.getEngineerById(id);
        JSONObject eObject=JSONObject.fromObject(engineer);
        view.setViewName("member/member_edit");
        view.addObject("engineer", eObject);
        return view;
    }
    /**
     *显示用户详细页面
     */
    @RequestMapping(value = "/page/showEngineerDetail/{id}", method = RequestMethod.GET)
    public ModelAndView showProjectDetail(HttpSession session, @PathVariable Integer id) {
    	ModelAndView view = new ModelAndView();
        Engineer engineer= engineerService.getEngineerById(id);
        JSONObject eObject=JSONObject.fromObject(engineer);
        view.addObject("engineer", eObject);
        view.setViewName("member/member_detail");
        return view;
    }

    /**
     *  首页
     *  获取工程师数
     *  
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/getEngineerData", method = RequestMethod.GET)
    public
    @ResponseBody
    ReturnDataInfo<EngineerPos> getEngineerDistribute(HttpSession session, HttpServletRequest request) {
        try {
        	List<EngineerPos> engineerPos=engineerService.getEngineerPosList();
            return ReturnDataInfo.createSuccessfulExecuteResults(engineerPos);
        } catch (Exception ex) {
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }
    /**
     *  （工程师/项目数）月度趋势
     *  
     */
    @RequestMapping(value = "/getMonthlyDataTrend", method = RequestMethod.GET)
    public
    @ResponseBody
    ReturnDataInfo<EngineerPos> getMonthlyDataTrend(HttpSession session, HttpServletRequest request) {
        try {
        	List<EngineerPos> engineerPos=engineerService.getEngineerPosList();
            return ReturnDataInfo.createSuccessfulExecuteResults(engineerPos);
        } catch (Exception ex) {
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }
    /**
     *  
     *  新增或修改工程师用户 
     *  
     */
    @RequestMapping(value = "/saveOrgUpdateEngineer", method = RequestMethod.POST, headers = "Content-Type=application/json")
    public
    @ResponseBody
    ReturnDataInfo<String> saveOrUpdateEngineer(HttpSession session, HttpServletRequest request,@RequestBody Engineer engineer) {
        try {
            
        	engineerService.saveOrUpdateEngineer(engineer);
        	
            return ReturnDataInfo.createSuccessfulSingleExecuteResult(null);
        } catch (Exception ex) {
        	logger.error("错误："+ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }
    /**
     * 根据ID获取项目详细信息
     */
    @RequestMapping(value = "/getMemberDetail/{id}", method = RequestMethod.GET)
    public  @ResponseBody ReturnDataInfo<Map<String, Object>> getMemberDetail(HttpSession session, @PathVariable Integer id) {
    	Map<String, Object>  map=  engineerService.getEngineerDetailById(id);
        return ReturnDataInfo.createSuccessfulSingleExecuteResult(map);
    }
    /**
     * 
     * 获取省份列表数据
     * 
     */
    @SuppressWarnings("unchecked")
	@RequestMapping(value = "/getProvinceDataList", method = RequestMethod.GET)
    public
    @ResponseBody
    ReturnDataInfo<StatisData> getProvinceDataList(HttpSession session, HttpServletRequest request, @RequestParam(value = "iDisplayStart", required = false, defaultValue = "0") Integer offset, @RequestParam(value = "iDisplayLength", required = false, defaultValue = "10") Integer limit, @RequestParam(value = "globalSearch", required = false, defaultValue = "{}") String globalSearch) {
        try {
            Map paramters = new HashMap();
            if (globalSearch != null) {
                JSONObject jsonObject = JSONObject.fromObject(globalSearch);
                paramters.putAll(jsonObject);
            }
            paramters.putAll(request.getParameterMap());
            List<StatisData> engineers = engineerService.findStatisDataListByMap(paramters, offset, limit);
            Integer totalCount = engineerService.findStatisDataCountByMap(paramters);
             return ReturnDataInfo.createSuccessfulExecuteResults(engineers, offset, limit, totalCount.longValue());
        } catch (Exception ex) {
            logger.error("获取省份用户列表失败", ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }
	/**
	 * 获取城市列表数据
	 * 
	 */
	@SuppressWarnings({ "unchecked", "unchecked" })
	@RequestMapping(value = "/getCityDataList", method = RequestMethod.GET)
    public
    @ResponseBody
    ReturnDataInfo<StatisData> getCityDataList(HttpSession session, HttpServletRequest request, @RequestParam(value = "iDisplayStart", required = false, defaultValue = "0") Integer offset, @RequestParam(value = "iDisplayLength", required = false, defaultValue = "10") Integer limit, @RequestParam(value = "globalSearch", required = false, defaultValue = "{}") String globalSearch) {
        try {
            Map paramters = new HashMap();
            if (globalSearch != null) {
                JSONObject jsonObject = JSONObject.fromObject(globalSearch);
                paramters.putAll(jsonObject);
            }
            paramters.putAll(request.getParameterMap());
            List<StatisData> engineers = engineerService.getStatisCityDataByMap(paramters, offset, limit);
            Integer totalCount = engineerService.findStatisCityDataCountByMap(paramters);
             return ReturnDataInfo.createSuccessfulExecuteResults(engineers, offset, limit, totalCount.longValue());
        } catch (Exception ex) {
            logger.error("获取城市用户列表失败", ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }
	/**
	 * 获取全国省市统计数据
	 * 
	 */
	@RequestMapping(value = "/getChinaAllEngineerData", method = RequestMethod.GET)
    public
    @ResponseBody
    ReturnDataInfo<ChinaData> getChinaAllEngineerData(HttpSession session, HttpServletRequest request) {
        try {
        	@SuppressWarnings("unchecked")
			List<ChinaData> chinaDatas= (List<ChinaData>) redisCache.getCacheValue(SecurityContant.CHINA_NAMESPACE, CHINA_STATIS_KEY);
        	if(null==chinaDatas){
        		chinaDatas=engineerService.getChinaAllEngineerDataList();
        		if(null==chinaDatas){
        			throw new BusinessException("获取全国统计数据为空！");
        		}
        		redisCache.addCache(SecurityContant.CHINA_NAMESPACE, CHINA_STATIS_KEY, chinaDatas,EXPIRE_TIME , TimeUnit.MINUTES);
        	}
            return ReturnDataInfo.createSuccessfulExecuteResults(chinaDatas);
        } catch (Exception ex) {
        	logger.error("获取全国数据异常！",ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }
	static{
		String expireTime=SystemConfig.getConfig("experiTime");
		if(StringUtils.isNotBlank(expireTime)){
			EXPIRE_TIME=Long.valueOf(expireTime);
			logger.info("缓存失效时间："+EXPIRE_TIME+"分钟");
		}
	}

}
